
var modifyOrAddFlag;
//初始化数据

	
  $(document).ready(function(){
		$('#win').window('close');

		//导入
		$('#import_link').window({
			width:465,
			modal:true,
			minimizable:false,
			maximizable:false,
			collapsible:false
		});
		$('#import_link').window('close');  //关闭窗口
		
		$("#selFileBtn").click(function(e){
			e.preventDefault();
			//$("#file").click();
		});
		
		$(".import_con").delegate("#importLinkFile" ,"change", function() {
		    $("#fileName").val($('#importLinkFile').val());
		    //clearAutofillStyle();
		});
		
		$(".button_con a" ).removeClass("l-btn-plain");
		$("#datagrid").datagrid({
			url : BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random(),
			method:'get',
			autoRowHeight:true,
			nowrap:false,
			pageSize:20,
			singleSelect:true,
			striped:true,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'name',title:'领域',width:100},
						{field:'remark',title:'备注',width:300,align:'left'}
			      ]],
			pagination:true,
			onSelect:function(rowIndex,rowData){
				$("#toolbar_edit").linkbutton('enable');
				$("#toolbar_delete").linkbutton('enable');
			},
			loadFilter:function(data){
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				
				param.sort = 'createTime,desc';
				param.name = $('#txtSearch').val();
				
				/*param.beginOfCreateTime = $('#txtBeginTime').datetimebox('getValue');
				param.endOfCreateTime = $('#txtEndTime').datetimebox('getValue');*/
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 

});
 
 	function add(){
 		modifyOrAddFlag = true;
 		$('#addForm')[0].reset();
 		$("#win").window('setTitle','领域管理-新增');
 		$('#win').window('open');
	}
 	//新增和修改
 	function save(){
 		if($("#addForm").form("validate")){
 	 		var name = $("#txtFieldName").val();
 	 		var remark = $("#txtRemark").val();
 	 		var newFieldInfo = {name:name,remark:remark};
 	 		var checkParam = {name:name};
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
	 		if(!modifyOrAddFlag){
	 	 		var row = $('#datagrid').datagrid('getSelected');
	 	 		checkParam.originalId = row.id;
	 	 		if(row.name == checkParam.name) // 未修改领域的名字，则可以直接修改
				{
	 	 			modifyField(newFieldInfo);
				}
				else
				{
					$.ajax({
			    		type: "get",
			    		url: BASE_URL_FIELD_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
			    		data: checkParam,
			    		contentType: "application/json",
			    		success: function(result) {
			    			if(result.isCanSave == true)
		    				{
			    				modifyField(newFieldInfo);
		    				}
		    				else 
	    					{
		    					if (result.errorCode == "DUPLICATE") 
								{
			    					$("#instance_save").linkbutton("enable");
			    					$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败，领域名称已存在！</p>","error");
								}
								else
								{
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败！</p>","error");
								}
	    					}
			    		},
						error: function() {
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('错误','<p>服务异常，修改领域信息失败，请稍后重试或联系管理员!</p>', 'error');
						}
			    	});
				}
	 		}else{
	 			$.ajax({
		    		type: "get",
		    		url: BASE_URL_FIELD_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
		    		data: checkParam,
		    		contentType: "application/json",
		    		success: function(result) {
	    				if(result.isCanSave == true)
	    				{
	    					addField(newFieldInfo);
	    				}
	    				else 
	    				{
	    					if (result.errorCode == "DUPLICATE") 
	    					{
	        					$("#instance_save").linkbutton("enable");
	        					$("#instance_save .l-btn-text").text("保存");
	    						$.messager.alert('错误',"<p>新增失败，领域名称已存在！</p>","error");
	    					}
	    					else
	    					{
	    						$("#instance_save").linkbutton("enable");
	    						$("#instance_save .l-btn-text").text("保存");
	    						$.messager.alert('错误',"<p>新增失败！</p>","error");
	    					}
	    				}
						
		    		},
					error: function() {
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						$.messager.alert('错误','<p>服务异常，新增领域失败，请稍后重试或联系管理员!</p>', 'error');
					}
		    	});
	 		}
 		}
 	}
 	
 	function addField(newFieldInfo) {
 		if(!newFieldInfo)
 		{
 	 		var name = $("#txtFieldName").val();
 	 		var remark = $("#txtRemark").val();
 	 		newFieldInfo = {name:name,remark:remark};
 		}
 		
 		var jsonData = JSON.stringify(newFieldInfo);
 		$.ajax({
			url: BASE_URL_FIELD_CRUD  + '?v=' + Math.random(),
			type:'post',
			contentType:"application/json",
			data:jsonData,
			success:function(){
				$.messager.alert("提示","<p>新增成功!</p>","info");
				$('#win').window('close');
				$("#datagrid").datagrid("reload",BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(){

				$.messager.alert("错误","<p>服务异常，新增领域失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
 	}
 	
 	function modifyField(newFieldInfo) {
 		var row = $('#datagrid').datagrid('getSelected');
 		if(!newFieldInfo)
 		{
 	 		var name = $("#txtFieldName").val();
 	 		var remark = $("#txtRemark").val();
 	 		newFieldInfo = {name:name,remark:remark};
 		}
 		
 		var jsonData = JSON.stringify(newFieldInfo);
 		$.ajax({
			url: BASE_URL_FIELD_CRUD + '/' + row.id  + '?v=' + Math.random(),
			type:'put',
			contentType:"application/json",
			data:jsonData,
			success:function(){
				$.messager.alert("提示","<p>修改成功!</p>","info");
				$('#win').window('close');
				$("#datagrid").datagrid("reload",BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(){
				$.messager.alert("错误","<p>服务异常，修改领域信息失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
 	}
 	//修改提示
 	function update(){
 		/*$("#win").window('setTitle','领域-修改');*/
 		var row = $('#datagrid').datagrid('getSelected');
 		if(row == null){
 			$.messager.alert('警告',"<p>请选中要修改的记录!</p>","warning");
 		}else{
 			modifyOrAddFlag = false;
 			$('#addForm')[0].reset();
 			$("#win").window('setTitle','领域管理-修改');
			$('#win').window('open');
			$("#txtFieldName").val(row.name).validatebox('validate');
 			$("#txtRemark").val(row.remark);
 			
			
			
		}
 	}
	
	//导入
	function import_link()
	{
		$('#import_link').window('open'); 
	}
	
 	//删除
 	function del(){
 		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要删除的记录!</p>","warning");
			return;
		}
 		var id = row.id;
 		var param = {id:id};
 		
 			$.ajax({
				url:BASE_URL_FIELD_SEARCH + '/checkIsCanDelete' + '?v=' + Math.random(),
				dataType:'json',
				type:'get',
				data:param,
				contentType:"application/json",
				success:function(result){
					if(result.isCanDelete){
						$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(r){
			 				if (r){
							 		$.ajax({
										url:BASE_URL_FIELD_CRUD + '/' + row.id  + '?v=' + Math.random(),
										dataType:'json',
										type:'delete',
										contentType:"application/json",
										success:function(){
											$.messager.alert('提示','<p>删除成功!</p>','info');
											$("#datagrid").datagrid("reload", BASE_URL_FIELD_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
										},
										error:function(){
											$.messager.alert("错误","<p>服务异常，删除领域失败，请重新登录或稍后再试！</p>","error");	
										}
							 		});
			 				}
			 			});
					}else{
						//alert("error");
						$.messager.alert('警告','<p>' + result.reason + '</p>','warning');
					}
				},
				error:function(){
					$.messager.alert('错误','<p>数据读取失败!</p>',"error");
				}
	 		});
 		
 		
 	}
 	
 	function subgo(){
 		if($("#importLinkFile").val() == "")
 		{
 			$.messager.alert("警告", "<p>请选择需要导入的.xls或.xlsx格式文件!</p>","warning");
 			return;
 		}
 		var tempArr = $("#importLinkFile").val().split(".");
 		var selFileType = tempArr[tempArr.length - 1];
 		if(selFileType != "xls" && selFileType != "xlsx")
 		{
 			$.messager.alert("警告", "<p>选择的文件格式有误，请选择.xls或.xlsx格式的文件!</p>","warning");
 			return;
 		}
 		
 		$("#buttons_inport .easyui-linkbutton").linkbutton("disable");
 		$("#buttons_inport .l-btn-text").text("正在导入...");
 		
 		//$("#import_form").submit();
 		$.ajaxFileUpload({
 	        url: '/api/importData/field/fileUpload' + "?name=" + encodeURI($("#fileName").val()), 
 	        type: 'post',
 	        secureuri: false, //一般设置为false
 	        fileElementId: 'importLinkFile', // 上传文件的id、name属性名
 	        dataType: 'text', //返回值类型，一般设置为json、application/json
 	        //data: {name:""}, //传递参数到服务器
 	        success: function(data, status){ 
 	        	//var resultObj = eval("[" + data.activeElement.innerText + "]")[0];
            	$("#fileName").val($('#importLinkFile').val());
         		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
         		$("#buttons_inport .l-btn-text").text("确定导入");
         		
 	        	var resultObj = JSON.parse(data.slice(data.indexOf(">") + 1,data.indexOf("</")));
 	            if(resultObj.backValue === true)
 	            {
 	            	$('#import_link').window('close'); 
 	            	$("#datagrid").datagrid("reload", BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random());
 	            	$.messager.alert('提示',"<p>导入成功！</p>","info");
 	            }
 	            else if(resultObj.backValue === false)
 	            {
 	            	$.messager.alert('错误',"<p>导入失败!所选文件内容为空或存在异常！</p>","error");
 	            }
 	            else
 	            {
 	            	$.messager.alert('错误',"<p>导入失败！" + resultObj.backValue + "</p>", "error"); 
 	            }
 	        },
 	        error: function(data, status, e){ 
	            $("#fileName").val($('#importLinkFile').val());
         		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
         		$("#buttons_inport .l-btn-text").text("确定导入");

				$.messager.alert("错误","<p>服务异常，导入失败，请重新登录或稍后再试！</p>","error");	
 	        }
 	    });
 	}
 	
 	
 	function onCancleEdit(){
 		$('#win').window('close');
 		$("#datagrid").datagrid("reload", BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random());
 	}

	function search(){
		
		//dataRetrieval('#txtBeginTime','#txtEndTime');
		$("#datagrid").datagrid("reload", BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random());
	}
	
	function rePage(){
		$('#win').window('close');
		$("#datagrid").datagrid("reload", BASE_URL_FIELD_SEARCH + '/findByExample' + '?v=' + Math.random());
	}